﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Quartz;
using Quartz.Core;
using ZilLion.Core.Log;
using ZilLion.TaskManager.Core;
using ZilLion.TaskManager.Core.Infrastructure;
using ZilLion.TaskManager.Core.Quartz;
using ZilLion.TaskManager.Entity.Entity;


namespace TaskRunnerConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                if (args.Any<string>())
                {
                    string taskjson = args[0].DecodeBase64();
                    CustomTaskLogger.Print(Loglevel.Trace, taskjson, "传入TaskRunnerConsole参数");
                    if (taskjson.IsNotNullOrEmpty())
                    {
                        TaskConfig config = JsonConvert.DeserializeObject<TaskConfig>(taskjson);
                        if (config != null)
                        {
                            IJob job = Activator.CreateInstance(GetClassInfo(config)) as IJob;
                            if (job != null)
                            {
                                CustomJobExecutionContext context = new CustomJobExecutionContext();
                                CustomJobDetailImpl impl = new CustomJobDetailImpl();
                                JobDataMap map = new JobDataMap();
                                Dictionary<string, object> t = new Dictionary<string, object>();
                                t.Add("taskconfig", config);
                                map.PutAll(t);
                                impl.JobDataMap = map;
                                context.JobDetail = impl;
                                job.Execute(context);
                            }
                        }

                    }
                }
            }
            catch (Exception exception)
            {
                CustomTaskLogger.Print(exception,"exe捕获Job 失败");
                //todo 发送 job 执行失败
            }

        }


        private static Type GetClassInfo(TaskConfig config)
        {
            return Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Package_" + config.TaskModule, config.TaskModule + ".dll")).GetTypes().FirstOrDefault(x => (x.Name == config.TaskAction));
        }

    }
}